<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"dttx123.gitee.io","root":"/blog/","scheme":"Gemini","version":"8.0.0-rc.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="nodejs基本介绍为什么要学习nodejs为什么要学习服务端的开发？  通过学习Node.js开发理解服务器开发、Web请求和响应过程、 了解服务器端如何与客户端配合 作为前端开发工程师（FE）需要具备一定的服务端开发能力  服务器端开发语言有很多，为什么要选择nodejs  降低编程语言切换的成本(nodejs实质上用的还是javascript) NodeJS是前端项目的基础设施，前端项目中用">
<meta property="og:type" content="article">
<meta property="og:title" content="node基础">
<meta property="og:url" content="http://dttx123.gitee.io/2018/05/05/nodejs/01-nodeJs%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="Starry Night">
<meta property="og:description" content="nodejs基本介绍为什么要学习nodejs为什么要学习服务端的开发？  通过学习Node.js开发理解服务器开发、Web请求和响应过程、 了解服务器端如何与客户端配合 作为前端开发工程师（FE）需要具备一定的服务端开发能力  服务器端开发语言有很多，为什么要选择nodejs  降低编程语言切换的成本(nodejs实质上用的还是javascript) NodeJS是前端项目的基础设施，前端项目中用">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-05-04T16:00:00.000Z">
<meta property="article:modified_time" content="2020-05-13T03:35:06.000Z">
<meta property="article:author" content="大春哥">
<meta property="article:tag" content="node">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://dttx123.gitee.io/2018/05/05/nodejs/01-nodeJs%E5%9F%BA%E7%A1%80/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>node基础 | Starry Night</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line toggle-line-first"></span>
        <span class="toggle-line toggle-line-middle"></span>
        <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Starry Night</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">这就朕为你打下的江山</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/05/05/nodejs/01-nodeJs%E5%9F%BA%E7%A1%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          node基础
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-05-05 00:00:00" itemprop="dateCreated datePublished" datetime="2018-05-05T00:00:00+08:00">2018-05-05</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:35:06" itemprop="dateModified" datetime="2020-05-13T11:35:06+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="nodejs基本介绍"><a href="#nodejs基本介绍" class="headerlink" title="nodejs基本介绍"></a>nodejs基本介绍</h1><h2 id="为什么要学习nodejs"><a href="#为什么要学习nodejs" class="headerlink" title="为什么要学习nodejs"></a>为什么要学习nodejs</h2><p>为什么要学习服务端的开发？</p>
<ol>
<li>通过学习Node.js开发理解<strong>服务器开发</strong>、<strong>Web请求和响应过程</strong>、 <strong>了解服务器端如何与客户端配合</strong></li>
<li>作为前端开发工程师（FE）需要具备一定的服务端开发能力</li>
</ol>
<p>服务器端开发语言有很多，为什么要选择nodejs</p>
<ol>
<li>降低编程语言切换的成本(nodejs实质上用的还是javascript)</li>
<li>NodeJS是前端项目的基础设施，前端项目中用到的大量工具 (大前端)  webpack  less-css</li>
<li><strong>对于前端工程师，面试时对于nodejs有一定的要求</strong></li>
</ol>
<ul>
<li><a href="https://www.zhipin.com/job_detail/d35a590c832162ed1XB42Ny-Flo~.html?ka=search_list_7" target="_blank" rel="noopener">web前端10-20k</a></li>
</ul>
<h2 id="node-js-是什么？"><a href="#node-js-是什么？" class="headerlink" title="node.js 是什么？"></a>node.js 是什么？</h2><p>node.js，也叫作node，或者nodejs，指的都是一个东西。</p>
<ol>
<li><a href="https://nodejs.org/" target="_blank" rel="noopener">node.js官方网站</a></li>
<li><a href="http://nodejs.cn/" target="_blank" rel="noopener">node.js中文网</a></li>
<li><a href="https://cnodejs.org/" target="_blank" rel="noopener">node.js 中文社区</a></li>
</ol>
<p>Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境，nodejs允许javascript代码运行在服务端</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">1. nodejs不是一门新的编程语言，nodejs是在服务端运行javascript的运行环境</span><br><span class="line">2. 运行环境：写得程序想要运行必须要有对应的运行环境</span><br><span class="line">	php代码必须要有apache服务器</span><br><span class="line">	在web端，浏览器就是javascript的运行环境</span><br><span class="line">	在node端，nodejs就是javascript的运行环境</span><br><span class="line">2. javascript并不只是能运行在浏览器端，浏览器端能够运行js是因为浏览器有js解析器，因此只需要有js解析器，任何软件都可以运行js。</span><br><span class="line">3. nodejs可以在服务端运行js，因为nodejs是基于chrome v8的js引擎。</span><br></pre></td></tr></table></figure>

<p><strong>nodejs的本质：不是一门新的编程语言，nodejs是javascript运行在服务端的运行环境，编程语言还是javascript</strong></p>
<h2 id="nodejs与浏览器的区别"><a href="#nodejs与浏览器的区别" class="headerlink" title="nodejs与浏览器的区别"></a>nodejs与浏览器的区别</h2><p>相同点：nodejs与浏览器都是javascript的运行环境，都能够解析js程序。对于ECMAScript语法来说，在nodejs和浏览器中都能运行。</p>
<p>不同点：nodejs无法使用DOM和BOM的操作，浏览器无法执行nodejs中的文件操作等功能</p>
<p>思考：</p>
<ol>
<li>在浏览器端，可以使用javascript操作数据库么？</li>
<li>在nodejs端，可以使用BOM和DOM的方法么？</li>
<li>我们学习nodejs，学习什么内容？ </li>
</ol>
<h2 id="nodejs可以干什么？"><a href="#nodejs可以干什么？" class="headerlink" title="nodejs可以干什么？"></a>nodejs可以干什么？</h2><ol>
<li>开发服务端程序</li>
<li>开发命令行工具（CLI），比如npm,webpack,gulp,less,sass等 vue-cli</li>
<li>开发桌面应用程序（借助 node-webkit、electron 等框架实现）</li>
</ol>
<h1 id="安装nodejs"><a href="#安装nodejs" class="headerlink" title="安装nodejs"></a>安装nodejs</h1><h2 id="nodejs版本"><a href="#nodejs版本" class="headerlink" title="nodejs版本"></a>nodejs版本</h2><p>下载地址</p>
<ul>
<li><a href="https://nodejs.org/en/download/" target="_blank" rel="noopener">当前版本</a></li>
<li><a href="https://nodejs.org/en/download/releases/" target="_blank" rel="noopener">历史版本</a></li>
</ul>
<p>官网术语解释</p>
<ul>
<li>LTS 版本：Long-term Support 版本，长期支持版，即稳定版。</li>
<li>Current 版本：Latest Features 版本，最新版本，新特性会在该版本中最先加入。</li>
</ul>
<p>查看node版本</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node -v</span><br></pre></td></tr></table></figure>

<h1 id="运行nodejs程序"><a href="#运行nodejs程序" class="headerlink" title="运行nodejs程序"></a>运行nodejs程序</h1><ul>
<li>创建js文件 <code>helloworld.js</code></li>
<li>写nodejs的内容：<code>console.log(&#39;hello nodejs&#39;)</code></li>
<li>打开命令窗口 <code>cmd</code><ul>
<li>shift加右键打开命令窗口，执行 <code>node 文件名.js</code>即可</li>
<li>给vscode安装<code>terminal</code>插件，直接在vscode中执行</li>
</ul>
</li>
<li>执行命令：<code>node helloworld.js</code></li>
</ul>
<p>注意：在nodejs中是无法使用DOM和BOM的内容的，因此<code>document, window</code>等内容是无法使用的。</p>
<h1 id="global模块-全局变量"><a href="#global模块-全局变量" class="headerlink" title="global模块-全局变量"></a>global模块-全局变量</h1><blockquote>
<p>Node.js 中的全局对象是 <code>global</code>, 类似于浏览器中的<code>window</code></p>
</blockquote>
<p>常用的global属性</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>: 用于打印日志</span><br><span class="line">setTimeout/clearTimeout: 设置清除延时器</span><br><span class="line">setInterval/clearInterval: 设置清除定时器</span><br><span class="line"></span><br><span class="line">__dirname: 当前文件的路径，不包括文件名</span><br><span class="line">__filename： 获取当前文件的路径，包括文件名</span><br><span class="line"></span><br><span class="line"><span class="comment">//与模块化相关的，模块化的时候会用到</span></span><br><span class="line"><span class="built_in">require</span></span><br><span class="line">exports</span><br><span class="line"><span class="built_in">module</span></span><br></pre></td></tr></table></figure>

<h1 id="fs模块"><a href="#fs模块" class="headerlink" title="fs模块"></a>fs模块</h1><blockquote>
<p>fs模块是nodejs中最常用的一个模块，因此掌握fs模块非常的有必要，fs模块的方法非常多,用到了哪个查哪个即可。</p>
<p>文档地址：<a href="http://nodejs.cn/api/fs.html" target="_blank" rel="noopener">http://nodejs.cn/api/fs.html</a></p>
</blockquote>
<p>  在nodejs中，提供了fs模块，这是node的核心模块</p>
<p>  注意：</p>
<ol>
<li>除了global模块中的内容可以直接使用，其他模块都是需要加载的。</li>
<li>fs模块不是全局的，不能直接使用。因此需要导入才能使用。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">"fs"</span>);</span><br></pre></td></tr></table></figure>

<h2 id="读取文件"><a href="#读取文件" class="headerlink" title="读取文件"></a>读取文件</h2><blockquote>
<p>语法：fs.readFile(path[, options], callback)</p>
</blockquote>
<p>方式一：不传编码参数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1： 文件的名字</span></span><br><span class="line"><span class="comment">//参数2： 读取文件的回调函数</span></span><br><span class="line">  <span class="comment">//参数1：错误对象，如果读取失败，err会包含错误信息，如果读取成功，err是null</span></span><br><span class="line">  <span class="comment">//参数2：读取成功后的数据（是一个Buffer对象）</span></span><br><span class="line">fs.readFile(<span class="string">"data.txt"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err);</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>方式二：传编码参数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1： 文件的路径</span></span><br><span class="line"><span class="comment">//参数2： 编码，如果设置了，返回一个字符串，如果没有设置，会返回一个buffer对象</span></span><br><span class="line"><span class="comment">//参数3： 回调函数</span></span><br><span class="line">fs.readFile(<span class="string">"data.txt"</span>, <span class="string">"utf8"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err);</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>关于Buffer对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> Buffer对象是Nodejs用于处理二进制数据的。</span><br><span class="line"><span class="number">2.</span> 其实任意的数据在计算机底层都是二进制数据，因为计算机只认识二进制。</span><br><span class="line"><span class="number">3.</span> 所以读取任意的文件，返回的结果都是二进制数据，即Buffer对象</span><br><span class="line"><span class="number">4.</span> Buffer对象可以调用toString()方法转换成字符串。</span><br></pre></td></tr></table></figure>

<h2 id="写文件"><a href="#写文件" class="headerlink" title="写文件"></a>写文件</h2><blockquote>
<p>语法：fs.writeFile(file, data[, options], callback)</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1：写入的文件名(如果文件不存在，会自动创建)</span></span><br><span class="line"><span class="comment">//参数2：写入的文件内容（注意：写入的内容会覆盖以前的内容）</span></span><br><span class="line"><span class="comment">//参数3：写文件后的回调函数</span></span><br><span class="line">fs.writeFile(<span class="string">"2.txt"</span>, <span class="string">"hello world, 我是一个中国人"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">"写入文件失败"</span>, err);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"写入文件成功"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>注意：</p>
<ol>
<li>写文件的时候，会把原来的内容给覆盖掉</li>
</ol>
<h2 id="追加文件"><a href="#追加文件" class="headerlink" title="追加文件"></a>追加文件</h2><blockquote>
<p>语法：fs.appendFile(path, data[, options], callback)</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1：追加的文件名(如果文件不存在，会自动创建)</span></span><br><span class="line"><span class="comment">//参数2：追加的文件内容（注意：写入的内容会覆盖以前的内容）</span></span><br><span class="line"><span class="comment">//参数3：追加文件后的回调函数</span></span><br><span class="line">fs.appendFile(<span class="string">"2.txt"</span>, <span class="string">"我是追加的内容"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">"追加文件内容失败"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"追加文件内容成功"</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>思考：如果没有appendFile，通过readFile与writeFile应该怎么实现？</p>
<h2 id="文件同步与异步的说明"><a href="#文件同步与异步的说明" class="headerlink" title="文件同步与异步的说明"></a>文件同步与异步的说明</h2><blockquote>
<p>fs中所有的文件操作，都提供了异步和同步两种方式</p>
</blockquote>
<p>异步方式：不会阻塞代码的执行</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//异步方式</span></span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">"fs"</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">111</span>);</span><br><span class="line">fs.readFile(<span class="string">"2.txt"</span>, <span class="string">"utf8"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">"读取文件失败"</span>, err);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"222"</span>);</span><br></pre></td></tr></table></figure>

<p>同步方式：会阻塞代码的执行</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//同步方式</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">111</span>);</span><br><span class="line"><span class="keyword">var</span> result = fs.readFileSync(<span class="string">"2.txt"</span>, <span class="string">"utf-8"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(result);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">222</span>);</span><br></pre></td></tr></table></figure>

<p>总结：同步操作使用虽然简单，但是会影响性能，因此尽量使用异步方法，尤其是在工作过程中。</p>
<h2 id="其他api（了解）"><a href="#其他api（了解）" class="headerlink" title="其他api（了解）"></a>其他api（了解）</h2><p>方法有很多，但是用起来都非常的简单，学会查文档</p>
<p>文档：<a href="http://nodejs.cn/api/fs.html" target="_blank" rel="noopener">http://nodejs.cn/api/fs.html</a></p>
<table>
<thead>
<tr>
<th>方法名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>fs.readFile(path, callback)</code></td>
<td>读取文件内容（异步）</td>
</tr>
<tr>
<td><code>fs.readFileSync(path)</code></td>
<td>读取文件内容（同步）</td>
</tr>
<tr>
<td><code>fs.writeFile(path, data, callback)</code></td>
<td>写入文件内容（异步）</td>
</tr>
<tr>
<td><code>fs.writeFileSync(path, data)</code></td>
<td>写入文件内容（同步）</td>
</tr>
<tr>
<td><code>fs.appendFile(path, data, callback)</code></td>
<td>追加文件内容（异步）</td>
</tr>
<tr>
<td><code>fs.appendFileSync(path, data)</code></td>
<td>追加文件内容（同步）</td>
</tr>
<tr>
<td><code>fs.rename(oldPath, newPath, callback)</code></td>
<td>重命名文件（异步）</td>
</tr>
<tr>
<td><code>fs.renameSync(oldPath, newPath)</code></td>
<td>重命名文件（同步）</td>
</tr>
<tr>
<td><code>fs.unlink(path, callback)</code></td>
<td>删除文件（异步）</td>
</tr>
<tr>
<td><code>fs.unlinkSync(path)</code></td>
<td>删除文件（同步）</td>
</tr>
<tr>
<td><code>fs.mkdir(path, mode, callback)</code></td>
<td>创建文件夹（异步）</td>
</tr>
<tr>
<td><code>fs.mkdirSync(path, mode)</code></td>
<td>创建文件夹（同步）</td>
</tr>
<tr>
<td><code>fs.rmdir(path, callback)</code></td>
<td>删除文件夹（异步）</td>
</tr>
<tr>
<td><code>fs.rmdirSync(path)</code></td>
<td>删除文件夹（同步）</td>
</tr>
<tr>
<td><code>fs.readdir(path, option, callback)</code></td>
<td>读取文件夹内容（异步）</td>
</tr>
<tr>
<td><code>fs.readdirSync(path, option)</code></td>
<td>读取文件夹内容（同步）</td>
</tr>
<tr>
<td><code>fs.stat(path, callback)</code></td>
<td>查看文件状态（异步）</td>
</tr>
<tr>
<td><code>fs.statSync(path)</code></td>
<td>查看文件状态（同步）</td>
</tr>
</tbody></table>
<h1 id="path模块"><a href="#path模块" class="headerlink" title="path模块"></a>path模块</h1><h2 id="路径操作的问题"><a href="#路径操作的问题" class="headerlink" title="路径操作的问题"></a>路径操作的问题</h2><p>在读写文件的时候，文件路径可以写相对路径或者绝对路径</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//data.txt是相对路径，读取当前目录下的data.txt, 相对路径相对的是指向node命令的路径</span></span><br><span class="line"><span class="comment">//如果node命令不是在当前目录下执行就会报错， 在当前执行node命令的目录下查找data.txt，找不到</span></span><br><span class="line">fs.readFile(<span class="string">"data.txt"</span>, <span class="string">"utf8"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"读取文件失败"</span>, err);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>相对路径：相对于执行node命令的路径</p>
<p>绝对路径：<code>__dirname</code>: 当前文件的目录，<code>__filename</code>: 当前文件的目录，包含文件名</p>
<h2 id="path模块的常用方法"><a href="#path模块的常用方法" class="headerlink" title="path模块的常用方法"></a>path模块的常用方法</h2><blockquote>
<p>关于路径，在linux系统中，路径分隔符使用的是<code>/</code>，但是在windows系统中，路径使用的<code>\</code></p>
</blockquote>
<p>在我们拼写路径的时候会带来很多的麻烦，经常会出现windows下写的代码，在linux操作系统下执行不了，path模块就是为了解决这个问题而存在的。</p>
<p>常用方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">path.join();<span class="comment">//拼接路径</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//windows系统下</span></span><br><span class="line">&gt; path.join(<span class="string">"abc"</span>,<span class="string">"def"</span>,<span class="string">"gg"</span>, <span class="string">"index.html"</span>)</span><br><span class="line"><span class="string">"abc\def\gg\a.html"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//linux系统下</span></span><br><span class="line">&gt; path.join(<span class="string">"abc"</span>,<span class="string">"def"</span>,<span class="string">"gg"</span>, <span class="string">"index.html"</span>)</span><br><span class="line"><span class="string">'abc/def/gg/index.html'</span></span><br><span class="line"></span><br><span class="line">path.basename(path[, ext])	返回文件的最后一部分</span><br><span class="line">path.dirname(path)	返回路径的目录名</span><br><span class="line">path.extname(path)	获取路径的扩展名</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> path = <span class="built_in">require</span>(<span class="string">"path"</span>);</span><br><span class="line"><span class="keyword">var</span> temp = <span class="string">"abc\\def\\gg\\a.html"</span>;</span><br><span class="line"><span class="built_in">console</span>.log(path.basename(temp));<span class="comment">//a.html</span></span><br><span class="line"><span class="built_in">console</span>.log(path.dirname(temp));<span class="comment">//abc\def\gg</span></span><br><span class="line"><span class="built_in">console</span>.log(path.extname(temp));<span class="comment">//.html</span></span><br></pre></td></tr></table></figure>

<p>【优化读写文件的代码】</p>
<h2 id="path模块其他api（了解）"><a href="#path模块其他api（了解）" class="headerlink" title="path模块其他api（了解）"></a>path模块其他api（了解）</h2><table>
<thead>
<tr>
<th>方法名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>path.basename(path[, ext])</code></td>
<td>返回文件的最后一部分</td>
</tr>
<tr>
<td><code>path.dirname(path)</code></td>
<td>返回路径的目录名</td>
</tr>
<tr>
<td><code>path.extname(path)</code></td>
<td>获取路径的扩展名</td>
</tr>
<tr>
<td><code>path.isAbsolute(path)</code></td>
<td>判断目录是否是绝对路径</td>
</tr>
<tr>
<td><code>path.join([...paths])</code></td>
<td>将所有的path片段拼接成一个规范的路径</td>
</tr>
<tr>
<td><code>path.normalize(path)</code></td>
<td>规范化路径</td>
</tr>
<tr>
<td><code>path.parse(path)</code></td>
<td>将一个路径解析成一个path对象</td>
</tr>
<tr>
<td><code>path.format(pathObj)</code></td>
<td>讲一个path对象解析成一个规范的路径</td>
</tr>
</tbody></table>
<h1 id="http模块"><a href="#http模块" class="headerlink" title="http模块"></a>http模块</h1><p>复习：</p>
<p>​    1- 输入网址浏览器的请求过程</p>
<p>​    2- http协议的构成</p>
<h2 id="创建服务器基本步骤"><a href="#创建服务器基本步骤" class="headerlink" title="创建服务器基本步骤"></a>创建服务器基本步骤</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 导入http模块，http模块是node的核心模块，作用是用来创建http服务器的。</span></span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//2. 创建服务器</span></span><br><span class="line"><span class="keyword">var</span> server = http.createServer();</span><br><span class="line"></span><br><span class="line"><span class="comment">//3. 服务器处理请求</span></span><br><span class="line">server.on(<span class="string">"request"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"我接收到请求了"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//4. 启动服务器，监听某个端口</span></span><br><span class="line">server.listen(<span class="number">9999</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"服务器启动成功了, 请访问： http://localhost:9999"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>详细说明</p>
<ol>
<li>给服务器注册request事件，只要服务器接收到了客户端的请求，就会触发request事件</li>
<li>request事件有两个参数，request表示请求对象，可以获取所有与请求相关的信息，response是响应对象，可以设置所有与响应相关的信息。</li>
<li>服务器监听的端口范围为：1-65535之间，推荐使用3000以上的端口，因为3000以下的端口一般留给系统使用</li>
</ol>
<h2 id="request对象详解"><a href="#request对象详解" class="headerlink" title="request对象详解"></a>request对象详解</h2><p>文档地址：<a href="http://nodejs.cn/api/http.html#http_message_headers" target="_blank" rel="noopener">http://nodejs.cn/api/http.html#http_message_headers</a></p>
<p>常见属性：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">headers: 所有的请求头信息</span><br><span class="line">method： 请求的方式</span><br><span class="line">url： 请求的地址</span><br></pre></td></tr></table></figure>

<p>注意：在发送请求的时候，可能会出现两次请求的情况，这是因为谷歌浏览器会自动增加一个<code>favicon.ico</code>的请求。</p>
<p>小结：request对象中，常用的就是method和url两个参数</p>
<h2 id="response对象详解"><a href="#response对象详解" class="headerlink" title="response对象详解"></a>response对象详解</h2><p>文档地址：<a href="http://nodejs.cn/api/http.html#http_class_http_serverresponse" target="_blank" rel="noopener">http://nodejs.cn/api/http.html#http_class_http_serverresponse</a></p>
<p>常见的属性和方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">res.write(data): 给浏览器发送请求体，可以调用多次，从而提供连续的请求体</span><br><span class="line">res.end();   通知服务器，所有响应头和响应主体都已被发送，即服务器将其视为已完成。</span><br><span class="line">res.end(data); 结束请求，并且响应一段内容，相当于res.write(data) + res.end()</span><br><span class="line">res.statusCode: 响应的的状态码 <span class="number">200</span> <span class="number">404</span> <span class="number">500</span></span><br><span class="line">res.statusMessage: 响应的状态信息， OK Not Found ,会根据statusCode自动设置。</span><br><span class="line">res.setHeader(name, value); 设置响应头信息， 比如content-type</span><br><span class="line">res.writeHead(statusCode, statusMessage, options); 设置响应头，同时可以设置状态码和状态信息。</span><br></pre></td></tr></table></figure>

<p><strong>注意：必须先设置响应头，才能设置响应。</strong> </p>
<h1 id="实现静态WEB服务器"><a href="#实现静态WEB服务器" class="headerlink" title="实现静态WEB服务器"></a>实现静态WEB服务器</h1><h2 id="服务器响应首页"><a href="#服务器响应首页" class="headerlink" title="服务器响应首页"></a>服务器响应首页</h2><ul>
<li>注意：浏览器中输入的URL地址，仅仅是一个标识，不与服务器中的目录一致。也就是说：返回什么内容是由服务端的逻辑决定</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">server.on(<span class="string">'request'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> url = req.url</span><br><span class="line">  <span class="keyword">if</span>(url === <span class="string">'/'</span>) &#123;</span><br><span class="line">    fs.readFile(<span class="string">'./index.html'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="keyword">return</span> res.end(<span class="string">'您访问的资源不存在~'</span>)</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      res.end(data)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="根据根据不同url，响应不同文件"><a href="#根据根据不同url，响应不同文件" class="headerlink" title="根据根据不同url，响应不同文件"></a>根据根据不同url，响应不同文件</h2><h2 id="content-type设置-MIME类型"><a href="#content-type设置-MIME类型" class="headerlink" title="content-type设置-MIME类型"></a>content-type设置-MIME类型</h2><ul>
<li>MIME(Multipurpose Internet Mail Extensions)多用途Internet邮件扩展类型 是一种表示文档性质和格式的标准化方式</li>
<li>浏览器通常使用MIME类型（而不是文件扩展名）来确定如何处理文档；因此服务器将正确的MIME类型附加到响应对象的头部是非常重要的</li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types" target="_blank" rel="noopener">MIME 类型</a></li>
</ul>
<h2 id="静态资源的通用处理"><a href="#静态资源的通用处理" class="headerlink" title="静态资源的通用处理"></a>静态资源的通用处理</h2><h2 id="MIME类型的通用处理-mime模块"><a href="#MIME类型的通用处理-mime模块" class="headerlink" title="MIME类型的通用处理-mime模块"></a>MIME类型的通用处理-mime模块</h2><ul>
<li>作用：获取文件的MIME类型</li>
<li>安装：<code>npm i mime</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mime = <span class="built_in">require</span>(<span class="string">'mime'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取路径对应的MIME类型</span></span><br><span class="line">mime.getType(<span class="string">'txt'</span>)                    <span class="comment">// ⇨ 'text/plain'</span></span><br><span class="line"><span class="comment">// 根据MIME获取到文件后缀名</span></span><br><span class="line">mime.getExtension(<span class="string">'text/plain'</span>)        <span class="comment">// ⇨ 'txt'</span></span><br></pre></td></tr></table></figure>

<h1 id="npm-Node包管理工具"><a href="#npm-Node包管理工具" class="headerlink" title="npm - Node包管理工具"></a>npm - Node包管理工具</h1><h2 id="npm的基本概念"><a href="#npm的基本概念" class="headerlink" title="npm的基本概念"></a>npm的基本概念</h2><ul>
<li>node package manager</li>
<li><a href="https://npmjs.com" target="_blank" rel="noopener">npm官网</a></li>
<li><a href="https://www.npmjs.com.cn/" target="_blank" rel="noopener">npm中文文档</a></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1. npm 是node的包管理工具，</span><br><span class="line">2. 它是世界上最大的软件注册表，每星期大约有 30 亿次的下载量，包含超过 600000 个 包（package） （即，代码模块）。</span><br><span class="line">3. 来自各大洲的开源软件开发者使用 npm 互相分享和借鉴。包的结构使您能够轻松跟踪依赖项和版本。</span><br></pre></td></tr></table></figure>

<ul>
<li>作用：通过<code>npm</code>来快速安装开发中使用的包</li>
<li>npm不需要安装，只要安装了node，就自带了<code>npm</code></li>
</ul>
<h2 id="npm基本使用"><a href="#npm基本使用" class="headerlink" title="npm基本使用"></a>npm基本使用</h2><h3 id="初始化包"><a href="#初始化包" class="headerlink" title="初始化包"></a>初始化包</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm init;    <span class="comment">//这个命令用于初始化一个包，创建一个package.json文件，我们的项目都应该先执行npm init</span></span><br><span class="line">npm init -y;  <span class="comment">//快速的初始化一个包， 不能是一个中文名</span></span><br></pre></td></tr></table></figure>

<h3 id="安装包"><a href="#安装包" class="headerlink" title="安装包"></a>安装包</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">npm install 包名;  <span class="comment">//安装指定的包名的最新版本到项目中</span></span><br><span class="line">npm install 包名@版本号;  <span class="comment">//安装指定包的指定版本</span></span><br><span class="line"></span><br><span class="line">npm i 包名； <span class="comment">//简写</span></span><br></pre></td></tr></table></figure>

<h3 id="卸载包"><a href="#卸载包" class="headerlink" title="卸载包"></a>卸载包</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm uninstall 包名;  <span class="comment">//卸载已经安装的包</span></span><br></pre></td></tr></table></figure>

<h3 id="清除缓存"><a href="#清除缓存" class="headerlink" title="清除缓存"></a>清除缓存</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm cache clean -f <span class="comment">// 如果npm安装失败了，可以用这个命令来清除缓存</span></span><br></pre></td></tr></table></figure>

<h2 id="package-json文件"><a href="#package-json文件" class="headerlink" title="package.json文件"></a>package.json文件</h2><p>package.json文件，包（项目）描述文件，用来管理组织一个包（项目），它是一个纯JSON格式的。</p>
<ul>
<li>作用：描述当前项目（包）的信息，描述当前包（项目）的依赖项</li>
<li>如何生成：<code>npm init</code>或者<code>npm init -y</code></li>
<li>作用<ul>
<li>作为一个标准的包，必须要有<code>package.json</code>文件进行描述</li>
<li>一个项目的node_modules目录通常都会很大，不用拷贝node_modules目录，可以通过package.json文件配合<code>npm install</code>直接安装项目所有的依赖项</li>
</ul>
</li>
<li>描述内容</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"name"</span>: <span class="string">"03-npm"</span>,  <span class="comment">//描述了包的名字，不能有中文</span></span><br><span class="line">  <span class="attr">"version"</span>: <span class="string">"1.0.0"</span>,  <span class="comment">//描述了包的的版本信息， x.y.z  如果只是修复bug，需要更新Z位。如果是新增了功能，但是向下兼容，需要更新Y位。如果有大变动，向下不兼容，需要更新X位。</span></span><br><span class="line">  <span class="attr">"description"</span>: <span class="string">""</span>, <span class="comment">//包的描述信息</span></span><br><span class="line">  <span class="attr">"main"</span>: <span class="string">"index.js"</span>, <span class="comment">//入口文件（模块化加载规则的时候详细的讲）</span></span><br><span class="line">  <span class="attr">"scripts"</span>: &#123;  <span class="comment">//配置一些脚本，在vue的时候会用到，现在体会不到</span></span><br><span class="line">    <span class="attr">"test"</span>: <span class="string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"keywords"</span>: [],  <span class="comment">//关键字（方便搜索）</span></span><br><span class="line">  <span class="attr">"author"</span>: <span class="string">""</span>,  <span class="comment">//作者的信息</span></span><br><span class="line">  <span class="attr">"license"</span>: <span class="string">"ISC"</span>,  <span class="comment">//许可证，开源协议</span></span><br><span class="line">  <span class="attr">"dependencies"</span>: &#123;   <span class="comment">//重要，项目的依赖， 方便代码的共享  通过 npm install可以直接安装所有的依赖项</span></span><br><span class="line">    <span class="attr">"bootstrap"</span>: <span class="string">"^3.3.7"</span>,</span><br><span class="line">    <span class="attr">"jquery"</span>: <span class="string">"^3.3.1"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意：一个合法的package.json，必须要有name和version两个属性</strong> </p>
<h2 id="本地安装和全局安装"><a href="#本地安装和全局安装" class="headerlink" title="本地安装和全局安装"></a>本地安装和全局安装</h2><p>有两种方式用来安装 npm 包：本地安装和全局安装。选用哪种方式来安装，取决于你如何使用这个包。 </p>
<ul>
<li>全局安装：如果你想将其作为一个命令行工具，那么你应该将其安装到全局。这种安装方式后可以让你在任何目录下使用这个命令。比如less命令，webpack命令，hcc-md命令 。</li>
<li>本地安装：如果你自己的模块依赖于某个包，并通过 Node.js 的 <code>require</code> 加载，那么你应该选择本地安装，这种方式也是 <code>npm install</code> 命令的默认行为。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 全局安装,会把npm包安装到C:\Users\HUCC\AppData\Roaming\npm目录下，作为命令行工具使用</span></span><br><span class="line">npm install -g 包名;</span><br><span class="line"></span><br><span class="line"><span class="comment">//本地安装，会把npm包安装到当前项目的node_modules文件中，作为项目的依赖</span></span><br><span class="line">npm install 包名;</span><br></pre></td></tr></table></figure>

<h2 id="常见的命令行工具"><a href="#常见的命令行工具" class="headerlink" title="常见的命令行工具"></a>常见的命令行工具</h2><h3 id="nrm"><a href="#nrm" class="headerlink" title="nrm"></a>nrm</h3><ul>
<li>nrm：npm registry manager（npm仓库地址管理工具）</li>
<li>安装：<code>npm i -g nrm</code></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 带*表示当前正在使用的地址</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 查看仓库地址列表</span></span><br><span class="line">nrm ls</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 切换仓库地址</span></span><br><span class="line">nrm use taobao</span><br></pre></td></tr></table></figure>

<h3 id="nodemon-自动重启"><a href="#nodemon-自动重启" class="headerlink" title="nodemon 自动重启"></a>nodemon 自动重启</h3><ul>
<li>作用：监视到js文件修改后，自动重启node程序</li>
<li>安装：<code>npm i -g nodemon</code></li>
<li>使用：<code>nodemon app.js</code> 运行node程序</li>
</ul>
<h1 id="实现动态WEB服务器"><a href="#实现动态WEB服务器" class="headerlink" title="实现动态WEB服务器"></a>实现动态WEB服务器</h1><h2 id="在node中使用art-template"><a href="#在node中使用art-template" class="headerlink" title="在node中使用art-template"></a>在node中使用art-template</h2><ul>
<li><a href="https://aui.github.io/art-template/zh-cn/docs/" target="_blank" rel="noopener">文档</a></li>
<li>安装</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install art-template</span><br></pre></td></tr></table></figure>

<ul>
<li>核心方法</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 基于模板路径渲染模板</span></span><br><span class="line"><span class="comment">//参数1：文件的路径</span></span><br><span class="line"><span class="comment">//参数2：数据</span></span><br><span class="line"><span class="comment">//返回值：返回渲染后的内容</span></span><br><span class="line"><span class="comment">// template(filename, data)</span></span><br><span class="line"><span class="keyword">let</span> html = template(path.join(__dirname, <span class="string">"pages"</span>, <span class="string">"index.html"</span>), &#123;<span class="attr">name</span>:<span class="string">"大吉大利，今晚吃鸡"</span>&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>注意点：文件的路径必须是绝对路径</strong></p>
<h2 id="get请求处理-url模块"><a href="#get请求处理-url模块" class="headerlink" title="get请求处理-url模块"></a>get请求处理-url模块</h2><ul>
<li>说明：用于 URL 处理与解析</li>
<li>注意：通过url拿到的查询参数都是字符串格式</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入url模块</span></span><br><span class="line"><span class="keyword">var</span> url = <span class="built_in">require</span>(<span class="string">'url'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 解析 URL 字符串并返回一个 URL 对象</span></span><br><span class="line"><span class="comment">// 第一个参数：表示要解析的URL字符串</span></span><br><span class="line"><span class="comment">// 第二个参数：是否将query属性（查询参数）解析为一个对象，如果为：true，则query是一个对象</span></span><br><span class="line"><span class="keyword">var</span> ret = url.parse(<span class="string">'http://localhost:3000/details?id=1&amp;name=jack'</span>, <span class="literal">true</span>)</span><br><span class="line"><span class="built_in">console</span>.log(ret.query) <span class="comment">// &#123; id: '1', name: 'jack' &#125;</span></span><br></pre></td></tr></table></figure>

<h2 id="服务端重定向"><a href="#服务端重定向" class="headerlink" title="服务端重定向"></a>服务端重定向</h2><ul>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status" target="_blank" rel="noopener">HTTP 状态码说明</a></li>
<li><a href="http://shuai.be/archives/301-302-redirection/" target="_blank" rel="noopener">301 和 302</a></li>
<li>说明：服务端可以通过HTTP状态码让浏览器中的页面重定向</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">res.writeHead(<span class="number">302</span>, &#123;</span><br><span class="line">  <span class="string">'Location'</span>: <span class="string">'/'</span></span><br><span class="line">&#125;)</span><br><span class="line">res.end()</span><br></pre></td></tr></table></figure>

<h2 id="POST请求参数的处理"><a href="#POST请求参数的处理" class="headerlink" title="POST请求参数的处理"></a>POST请求参数的处理</h2><ul>
<li>说明：POST请求可以发送大量数据，没有大小限制</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接受POST参数</span></span><br><span class="line"><span class="keyword">var</span> postData = []</span><br><span class="line"></span><br><span class="line"><span class="comment">// data事件：用来接受客户端发送过来的POST请求数据</span></span><br><span class="line"><span class="keyword">var</span> result = <span class="string">""</span>;</span><br><span class="line">req.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">chunk</span>) </span>&#123;</span><br><span class="line">  result += chunk;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// end事件：当POST数据接收完毕时，触发</span></span><br><span class="line">req.on(<span class="string">'end'</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  cosnole.log(result); </span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="请求体处理-querystring模块"><a href="#请求体处理-querystring模块" class="headerlink" title="请求体处理-querystring模块"></a>请求体处理-querystring模块</h2><ul>
<li>用于解析与格式化 URL 查询字符串</li>
<li>注意：只在专门处理查询字符串时使用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// foo=bar&amp;abc=xyz&amp;abc=123</span></span><br><span class="line"><span class="keyword">var</span> querystring = <span class="built_in">require</span>(<span class="string">'querystring'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 将查询参数转化为对象</span></span><br><span class="line"><span class="comment">// 第一个参数: 要解析的 URL 查询字符串</span></span><br><span class="line">querystring.parse(<span class="string">'foo=bar&amp;abc=xyz'</span>) <span class="comment">// &#123; foo: 'bar', abc: 'xyz' &#125;</span></span><br></pre></td></tr></table></figure>


    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/node/" rel="tag"># node</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2018/04/09/ES6/ES601/" rel="prev" title="ES6基础">
      <i class="fa fa-chevron-left"></i> ES6基础
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/06/07/nodejs/02-%E6%A8%A1%E5%9D%97%E5%8C%96%E7%AC%94%E8%AE%B0/" rel="next" title="模块化">
      模块化 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#nodejs基本介绍"><span class="nav-text">nodejs基本介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么要学习nodejs"><span class="nav-text">为什么要学习nodejs</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#node-js-是什么？"><span class="nav-text">node.js 是什么？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#nodejs与浏览器的区别"><span class="nav-text">nodejs与浏览器的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#nodejs可以干什么？"><span class="nav-text">nodejs可以干什么？</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#安装nodejs"><span class="nav-text">安装nodejs</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#nodejs版本"><span class="nav-text">nodejs版本</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#运行nodejs程序"><span class="nav-text">运行nodejs程序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#global模块-全局变量"><span class="nav-text">global模块-全局变量</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#fs模块"><span class="nav-text">fs模块</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#读取文件"><span class="nav-text">读取文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#写文件"><span class="nav-text">写文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#追加文件"><span class="nav-text">追加文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文件同步与异步的说明"><span class="nav-text">文件同步与异步的说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他api（了解）"><span class="nav-text">其他api（了解）</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#path模块"><span class="nav-text">path模块</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#路径操作的问题"><span class="nav-text">路径操作的问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#path模块的常用方法"><span class="nav-text">path模块的常用方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#path模块其他api（了解）"><span class="nav-text">path模块其他api（了解）</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#http模块"><span class="nav-text">http模块</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建服务器基本步骤"><span class="nav-text">创建服务器基本步骤</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#request对象详解"><span class="nav-text">request对象详解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#response对象详解"><span class="nav-text">response对象详解</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实现静态WEB服务器"><span class="nav-text">实现静态WEB服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#服务器响应首页"><span class="nav-text">服务器响应首页</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#根据根据不同url，响应不同文件"><span class="nav-text">根据根据不同url，响应不同文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#content-type设置-MIME类型"><span class="nav-text">content-type设置-MIME类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#静态资源的通用处理"><span class="nav-text">静态资源的通用处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MIME类型的通用处理-mime模块"><span class="nav-text">MIME类型的通用处理-mime模块</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#npm-Node包管理工具"><span class="nav-text">npm - Node包管理工具</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#npm的基本概念"><span class="nav-text">npm的基本概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#npm基本使用"><span class="nav-text">npm基本使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#初始化包"><span class="nav-text">初始化包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装包"><span class="nav-text">安装包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#卸载包"><span class="nav-text">卸载包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#清除缓存"><span class="nav-text">清除缓存</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#package-json文件"><span class="nav-text">package.json文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本地安装和全局安装"><span class="nav-text">本地安装和全局安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常见的命令行工具"><span class="nav-text">常见的命令行工具</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#nrm"><span class="nav-text">nrm</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nodemon-自动重启"><span class="nav-text">nodemon 自动重启</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实现动态WEB服务器"><span class="nav-text">实现动态WEB服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#在node中使用art-template"><span class="nav-text">在node中使用art-template</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#get请求处理-url模块"><span class="nav-text">get请求处理-url模块</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务端重定向"><span class="nav-text">服务端重定向</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#POST请求参数的处理"><span class="nav-text">POST请求参数的处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#请求体处理-querystring模块"><span class="nav-text">请求体处理-querystring模块</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="大春哥"
      src="/blog/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">大春哥</p>
  <div class="site-description" itemprop="description">IT</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">35</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">大春哥</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

</body>
</html>
